import "./login.less";
import { Form, Button, Input, Toast } from "antd-mobile";
import logo from "@/assets/images/logo.png";
import { useState } from "react";
import { loginApi } from "@/api";
import { useNavigate } from "react-router-dom";
export default function Login() {
  const nav = useNavigate();

  // 当前是否是登录页
  const [isLoginPage, setIsLoginPage] = useState(true);

  const obj = {
    username: "12345678901",
    password: "wolfcode123",
  };

  const login = (values: LoginParams) => {
    loginApi(values).then((res) => {
      if (res?.errCode === 0) {
        // 弹出登录成功
        Toast.show({
          content: "登录成功",
          icon: "success",
        });
        // 存token到localStorage
        localStorage.setItem("token", res.data);
        // 跳转到首页
        nav("/home");
      }
    });
  };
  const register = () => {
    // 写注册的逻辑
  };

  const submit = (values: LoginParams) => {
    isLoginPage ? login(values) : register();
  };

  return (
    <div className="login">
      <div className="logo">
        <img src={logo} alt="" />
      </div>
      <Form
        initialValues={obj}
        onFinish={submit}
        layout="horizontal"
        footer={
          <Button block type="submit" color="primary" size="large">
            {isLoginPage ? "登录" : "注册"}
          </Button>
        }
      >
        <Form.Item
          name="username"
          rules={[
            { required: true, message: "手机号不能为空" },
            { pattern: /^[1]\d{10}$/, message: "请输入正确的手机号" },
          ]}
        >
          <Input placeholder="请输入手机" />
        </Form.Item>
        <Form.Item
          name="password"
          rules={[{ required: true, message: "密码不能为空" }]}
        >
          <Input placeholder="请输入密码" />
        </Form.Item>
      </Form>
      <div>
        <Button
          color="primary"
          fill="none"
          onClick={() => setIsLoginPage(!isLoginPage)}
        >
          去{isLoginPage ? "注册" : "登录"}
        </Button>
      </div>
    </div>
  );
}
